package com.sq.goodline.config;

import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.Filter;
import org.springframework.integration.annotation.Router;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.annotation.Transformer;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.ip.dsl.Udp;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;

import com.sq.goodline.service.UdpService;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class UdpServer {

	@Resource
    private UdpConfig udpconfig;
	@Autowired
    private UdpService udpService;
	
	@Bean
	public IntegrationFlow integrationFlow() {
		log.info("UDP服务启动，端口：{}",udpconfig.getListeningPort());
		return IntegrationFlows.from(Udp.inboundAdapter(udpconfig.getListeningPort())).channel("udpChannel").get();
	}
	
	@Transformer(inputChannel="udpChannel",outputChannel="udpFilter")
	public String transformer(@Payload byte[] payload,@Headers Map<String,Object> headers) {
		String traceId = UUID.randomUUID().toString().replace("-","");
		MDC.put("TraceId", traceId);
		String msg = new String(payload);
		log.debug("接收到UDP消息:{}",msg);
		//这里可对消息进行转换处理，暂无
		return msg;
	}
	
	/**
	 * 提前过滤消息，只处理指定ip的消息
	 * @param msg
	 * @param headers
	 * @return
	 */
	@Filter(inputChannel="udpFilter",outputChannel="udpRouter")
	public boolean filter(String msg,@Headers Map<String,Object> headers) {
		String remoteIP = headers.get("ip_address").toString();
		log.info("消息发送者IP：{}",remoteIP); 
		/*for(String allowIp:udpconfig.getAllowIpList()){
			if(allowIp.equals(remoteIP)) {
				return true;
			}
		}
		log.info("未知的发送者IP,拒绝处理");
		return false;*/
		return true;//交给阿里云安全组控制
	}
	
	/**
	 * 路由处理，可分发给不同处理器handler
	 * @param msg
	 * @param headers
	 * @return
	 */
	@Router(inputChannel="udpRouter")
	public String router(String msg,@Headers Map<String,Object> headers) {
		return "udpHandler";
	}
	
	/**
	 * 最终消息处理器
	 * @param msg
	 */
	@ServiceActivator(inputChannel="udpHandler")
	public void udpHandler(String msg) {
		udpService.doUdpMsg(msg);
	}
}
